package com.inkrl.user.service.v1;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.inkrl.user.domain.User;
import com.inkrl.user.enums.ResCode;
import com.inkrl.user.enums.UserParam;
import com.inkrl.user.mapper.UserMapper;
import com.inkrl.user.service.TokenService;
import com.inkrl.user.service.UserService;
import com.inkrl.user.until.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service("UserService")
public class UserServiceImp implements UserService {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private TokenService tokenService;


    @Override
    public HashMap<String, String> userLogin(String username,String password) throws JsonProcessingException {
        HashMap<String, String> responseMap = new HashMap<String, String>();
        //先校验登录信息，如果账号密码不正确，就返回不正确的信息
        HashMap<String,String> map = new HashMap<String,String>();
        map.put(UserParam.USERNAME,username);
        map.put(UserParam.PASSWORD,MD5Utils.md5(password));
        User user = userMapper.findByUserV2(map);
        if(user==null) {
            responseMap.put("msg", "账号或密码错误");
            responseMap.put("resCode", ResCode.USERLOGINERRO);
            return responseMap;
        }
        //生成新的token 该方法会直接删除已缓存的token 在生成没有就直接生成
        String token = tokenService.newToken(user);
        responseMap.put("token",token);
        responseMap.put("username",user.getUsername());
        responseMap.put("msg","登录成功");
        responseMap.put("resCode", ResCode.OK);
        return responseMap;
    }

    @Override
    public boolean isDuplicate(User user) {
        user = userMapper.findByUser(user);
        return user != null;
    }

    @Override
    public boolean isDuplicate(String param, String paramName) {
        HashMap<String,String> map = new HashMap<String,String>();
        map.put(paramName,param);
        User user = userMapper.findByUserV2(map);
        return user!=null;
    }

    @Override
    public void addUser(User user) {
        user.setPassword(MD5Utils.md5(user.getPassword()));
        userMapper.insertUser(user);
    }


}
